package com.arkopp.partyscanner;

import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class PartyScannerActivity extends Activity implements OnClickListener, Runnable {
	private ProgressDialog progressDialog;
	private String scannedData;
	private TextView txtname;
	private TextView txtemail;
	private ImageView imgguest;
	private TextView txtstatus;
	private Response objResponse;
	private ScannerConfig sc;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		txtname = (TextView) findViewById(R.id.txtName);
		txtemail = (TextView) findViewById(R.id.txtEmail);
		imgguest = (ImageView) findViewById(R.id.imgGuest);
		txtstatus = (TextView) findViewById(R.id.txtStatus);
		Button btnScan = (Button) findViewById(R.id.btnScan);
		btnScan.setOnClickListener(this);
		sc = ((ScannerConfig)getApplicationContext());

	}
	
    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
    	menu.add("Config");
    	return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
		switch (item.getItemId()) {
		case 0:
			Intent configIntent = new Intent(PartyScannerActivity.this, ConfigActivity.class);
			PartyScannerActivity.this.startActivity(configIntent);
			return true;
		}
		return super.onOptionsItemSelected(item);
    }
	
	public void onActivityResult(int requestCode, int resultCode, Intent intent) {
		if (requestCode == 0) {
			if (resultCode == RESULT_OK) {
				String qrContent = intent.getStringExtra("SCAN_RESULT");
				//String format = intent.getStringExtra("SCAN_RESULT_FORMAT");

				//QR Code Data:

				scannedData = qrContent;
				progressDialog = ProgressDialog.show(this, "Party Scanner", "Verifying...", true);
				Thread thread = new Thread(this);

				thread.start();
				// Handle successful scan
			} else if (resultCode == RESULT_CANCELED) {
				// Handle cancel
			}
		}
	}
	@Override
	public void onClick(View arg0) {
		// TODO Auto-generated method stub
		Intent intent = new Intent("com.google.zxing.client.android.SCAN");
		intent.putExtra("SCAN_MODE", "QR_CODE_MODE");
		startActivityForResult(intent, 0);
	}

	public void run() {
		String responseBody = "";
		try {


			HttpClient httpclient = new DefaultHttpClient();   
			HttpPost httppost = new HttpPost(sc.getCheckInURL() + "/index.php?r=client/checkin"); 
			// Add your data   
			List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(5);   
			nameValuePairs.add(new BasicNameValuePair("e", sc.getEventID()));
			nameValuePairs.add(new BasicNameValuePair("b", scannedData));

			try {
				httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
				try {
					HttpResponse response = httpclient.execute(httppost);
					responseBody = EntityUtils.toString(response.getEntity());
				} catch (ClientProtocolException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}


			ByteArrayInputStream in = new ByteArrayInputStream(responseBody.getBytes());
			InputSource is = new InputSource();
			is.setByteStream(in);


			/* Get a SAXParser from the SAXPArserFactory. */
			SAXParserFactory spf = SAXParserFactory.newInstance();
			SAXParser sp = spf.newSAXParser();

			/* Get the XMLReader of the SAXParser we created. */
			XMLReader xr = sp.getXMLReader();
			/* Create a new ContentHandler and apply it to the XML-Reader*/
			XMLHandler xmlhandler = new XMLHandler();
			xr.setContentHandler(xmlhandler);

			/* Parse the xml-data from our URL. */
			xr.parse(is);
			/* Our ExampleHandler now provides the parsed data to us. */
			Response r = xmlhandler.getParsedData();
			objResponse = r;
		} catch (Exception e) {
			e.printStackTrace();
		}
		handler.sendEmptyMessage(0);
	}
	
	
	public void GetLiveImage(String imgURL)
    {

		if (imgURL.equalsIgnoreCase("")) {
			imgguest.setAlpha(0);
		} else {
		
                     try {  

                             URL aURL = new URL(imgURL);  
                             URLConnection conn = aURL.openConnection();  
                             conn.connect();  
                             InputStream is = conn.getInputStream();  

                             BufferedInputStream bis = new BufferedInputStream(is);  

                             Bitmap bm = BitmapFactory.decodeStream(bis);  
                             bis.close();  
                             is.close();  

                             imgguest.setImageBitmap(bm);
                             imgguest.setAlpha(255);
                        } catch (IOException e) {  

                        	
                        }  
		}

    }

	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			if (objResponse.getStatus().equalsIgnoreCase("duplicate")) {
				//FAIL IT
				txtname.setText(objResponse.getFirstName() + " " + objResponse.getLastName());
				txtemail.setText(objResponse.getEmail());
					
				try {
					GetLiveImage(objResponse.getImageURL());
				} catch (NullPointerException n) {
					GetLiveImage("");
				}
				
				txtstatus.setBackgroundColor(Color.rgb(255, 165, 0));
				txtstatus.setText("DUPLICATE");
				
			} else if (objResponse.getStatus().equalsIgnoreCase("Good")) {
				//Success
				txtname.setText(objResponse.getFirstName() + " " + objResponse.getLastName());
				txtemail.setText(objResponse.getEmail());
				
				try {
					GetLiveImage(objResponse.getImageURL());
				} catch (NullPointerException n) {
					GetLiveImage("");
				}				
				
				txtstatus.setBackgroundColor(Color.GREEN);
				txtstatus.setText("GOOD");
			} else if (objResponse.getStatus().equalsIgnoreCase("Invalid")) {
				//Invalid
				txtname.setText("");
				txtemail.setText("");
				txtstatus.setBackgroundColor(Color.RED);
				txtstatus.setText("INVALID");
				GetLiveImage("");
			}
			progressDialog.dismiss();
		}
	};

}